<template>
  <div class="table-box">
    <ProTable
      ref="proTableRef"
      title="客户信息"
      :indent="20"
      :columns="columns"
      :search-columns="searchColumns"
      :request-api="getTableList"
      row-key="id"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button
          type="primary"
          v-auth="'basicclient_add'"
          :icon="CirclePlus"
          @click="openAddEdit('新增客户', { state: 1017001 })"
        >
          新增
        </el-button>
        <el-button v-auth="'teacher.statistics.import'" type="primary" :icon="Upload" @click="importData"> 导入 </el-button>
        <el-button v-auth="'teacher.statistics.export'" type="primary" :icon="Download" @click="downloadFile"> 导出 </el-button>
        <el-button
          v-auth="'basicclient_batchdel'"
          type="danger"
          :icon="Delete"
          plain
          :disabled="!scope.isSelected"
          @click="batchDelete(scope.selectedListIds)"
        >
          批量删除
        </el-button>
      </template>
      <template #state="scope">
        <el-switch
          v-model="scope.row.state"
          :active-value="1017001"
          :inactive-value="1017002"
          active-text="启用"
          inactive-text="禁用"
          inline-prompt
          :active-action-icon="Check"
          :inactive-action-icon="Close"
          :loading="switchLoading"
          :before-change="() => changeDataScope(scope.row)"
        />
      </template>
      <template #operation="{ row }">
        <el-button v-auth="'basicclient_edit'" type="primary" link :icon="EditPen" @click="openAddEdit('编辑客户', row, false)">
          编辑
        </el-button>
        <el-button v-auth="'basicclient_del'" type="primary" link :icon="Delete" @click="deleteInfo(row)"> 删除 </el-button>
      </template>
    </ProTable>
    <ClientForm ref="clientFormRef" />
    <ImportExcel ref="ImportExcelRef" />
  </div>
</template>
<script setup>
defineOptions({
  name: 'BasicClient'
});
import { h, ref } from 'vue';
import { CirclePlus, Delete, EditPen, Check, Close, Download, Upload } from '@element-plus/icons-vue';
import ProTable from '@/components/ProTable/index.vue';
import { useHandleData } from '@/hooks/useHandleData';
import ImportExcel from '@/components/ImportExcel/index.vue';
import {
  getClientList,
  createClient,
  updateClient,
  deleteClient,
  updateClientStatus,
  exportClient,
  importClient
} from '@/api/modules/basicinfo/client';
import ClientForm from './clientForm.vue';
import { useOptionsStore } from '@/stores/modules/options';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useDownload } from '@/hooks/useDownload';
const optionsStore = useOptionsStore();
const clientFormRef = ref();
const proTableRef = ref();
const switchLoading = ref(false);
// 表格配置项
const columns = [
  { type: 'selection', width: 80 },
  { prop: 'cName', label: '客户名称' },
  { prop: 'phone', label: '联系电话' },
  { prop: 'email', label: '邮箱' },
  { prop: 'address', label: '地址' },
  {
    prop: 'state',
    label: '状态',
    tag: true,
    enum: optionsStore.getDictOptions('basic_client_state'),
    fieldNames: { label: 'codeName', value: 'id', tagType: 'callbackShowStyle' }
  },
  { prop: 'orgName', label: '所在单位' },
  { prop: 'taxNum', label: '税号' },
  { prop: 'bankName', label: '开户行' },
  { prop: 'bankCard', label: '银行卡号' },
  { prop: 'billInfo', label: '发票信息' },
  { prop: 'remark', label: '备注' },
  { prop: 'creater_at', label: '创建时间', isShow: false },
  { prop: 'updata_at', label: '更新时间', isShow: false },
  { prop: 'creater_username', label: '创建人', isShow: false },
  { prop: 'updata_username', label: '更新人', isShow: false },
  { prop: 'operation', label: '操作', width: 200, fixed: 'right' }
];
// 搜索条件项
const searchColumns = [
  { prop: 'cName', label: '客户名称', el: 'input' },
  {
    prop: 'state',
    label: '状态',
    el: 'select',
    enum: optionsStore.getDictOptions('basic_client_state'),
    fieldNames: { label: 'codeName', value: 'id', tagType: 'callbackShowStyle' }
  },
  { prop: 'phone', label: '联系电话', el: 'input' }
];
// 获取table列表
const getTableList = params => {
  return getClientList(params);
};
// 打开 drawer(新增、查看、编辑)
const openAddEdit = async (title, row = {}, isAdd = true) => {
  const params = {
    title,
    row: { ...row },
    api: isAdd ? createClient : updateClient,
    getTableList: proTableRef.value?.getTableList,
    isAdd
  };
  clientFormRef.value?.acceptParams(params);
};
// 删除信息
const deleteInfo = async params => {
  await useHandleData(deleteClient, { ids: [params.id] }, `删除【${params.id}】客户`);
  proTableRef.value?.getTableList();
};
// 批量删除信息
const batchDelete = async ids => {
  await useHandleData(deleteClient, { ids }, '删除所选客户');
  proTableRef.value?.clearSelection();
  proTableRef.value?.getTableList();
};

const changeDataScope = params => {
  switchLoading.value = true;
  const handleSuccess = resolve => {
    setTimeout(() => {
      switchLoading.value = false;
      proTableRef.value?.getTableList();
      ElMessage.success('修改状态成功');
      resolve(true);
    }, 200);
  };

  const handleError = reject => {
    setTimeout(() => {
      switchLoading.value = false;
      reject();
    }, 200);
  };

  return new Promise((resolve, reject) => {
    if (params.state === 1017001) {
      ElMessageBox.confirm(`您确认要禁用 [${params.cName}] 客户吗? `, '温馨提示', {
        type: 'warning'
      })
        .then(() => {
          updateClientStatus({ id: params.id, state: params.state })
            .then(() => handleSuccess(resolve))
            .catch(() => handleError(reject));
        })
        .catch(() => {
          switchLoading.value = false;
        });
    } else {
      updateClientStatus({ id: params.id, state: params.state })
        .then(() => handleSuccess(resolve))
        .catch(() => handleError(reject));
    }
  });
};
// 导出
const downloadFile = async () => {
  ElMessageBox.confirm('确认导出数据?', '温馨提示', { type: 'warning' }).then(() => {
    let newParams = proTableRef.value?.searchParam;
    useDownload(exportClient, '客户信息', newParams);
  });
};

// 导入
const ImportExcelRef = ref();
const importData = () => {
  const params = {
    title: '客户信息',
    templateName: '当前下载【客户信息模板】',
    importApi: importClient,
    getTableList: proTableRef.value?.getTableList
  };
  ImportExcelRef.value?.acceptParams(params);
};
</script>
